package com.ai.notices.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.ai.notices.common.util.BeanUtil;
import com.ai.notices.common.util.PagedResult;
import com.ai.notices.dao.mysql.mapper.GdsInfoMapper;
import com.ai.notices.dao.mysql.mapper.IdentityCardMapper;
import com.ai.notices.dao.mysql.mapper.OrdInfoImpMapper;
import com.ai.notices.dao.mysql.mapper.OrdInfoMapper;
import com.ai.notices.dao.mysql.model.AuthStaff;
import com.ai.notices.dao.mysql.model.GdsInfo;
import com.ai.notices.dao.mysql.model.GdsInfoExample;
import com.ai.notices.dao.mysql.model.IdentityCard;
import com.ai.notices.dao.mysql.model.IdentityCardExample;
import com.ai.notices.dao.mysql.model.OrdInfo;
import com.ai.notices.dao.mysql.model.OrdInfoExample;
import com.ai.notices.dao.mysql.model.OrdInfoImp;
import com.ai.notices.dao.mysql.model.OrdInfoImpExample;
import com.ai.notices.service.interfaces.IOrderInfoSV;
import com.ai.notices.web.FileUtils;
import com.github.pagehelper.PageHelper;

/**
 * Created by huangzh on 17/4/13.
 */
@Service
public class OrdInfoSVImpl implements IOrderInfoSV {

    @Autowired
    private OrdInfoMapper ordInfoMapper;

    @Autowired
    private OrdInfoImpMapper ordInfoImpMapper;

    @Autowired
    private GdsInfoMapper gdsInfoMapper;

    @Autowired
    private IdentityCardMapper identityCardMapper;

	@Override
	public List<OrdInfo> queryOrdInfoLst(OrdInfo ordInfo) throws Exception {
		// TODO Auto-generated method stub
		return ordInfoMapper.selectExportByExample(ordInfo);
	}

	@Override
	public PagedResult<OrdInfo> queryOrdInfoByPage(OrdInfo ordInfo, Integer pageNo, Integer pageSize)
			throws Exception {
		// TODO Auto-generated method stub
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 10 : pageSize;
		PageHelper.startPage(pageNo, pageSize); // startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		OrdInfoExample example = new OrdInfoExample();
		OrdInfoExample.Criteria criteria = example.createCriteria();
		criteria.andStateEqualTo("1");
		if (StringUtils.isNotBlank(ordInfo.getBatchId())) {
			criteria.andBatchIdEqualTo(ordInfo.getBatchId());
		}
		if (StringUtils.isNotBlank(ordInfo.getExpressNo())) {
			criteria.andExpressNoEqualTo(ordInfo.getExpressNo());
		}
		if (StringUtils.isNotBlank(ordInfo.getIdentityCard())) {
			criteria.andIdentityCardEqualTo(ordInfo.getIdentityCard());
		}
		if (StringUtils.isNotBlank(ordInfo.getState())) {
			if ("1".equals(ordInfo.getState())) {
				criteria.andPayIdIsNotNull();
			} else {
				criteria.andPayIdIsNull();
			}
		}
		if (StringUtils.isNotBlank(ordInfo.getMainOrdId())) {
			criteria.andMainOrdIdEqualTo(ordInfo.getMainOrdId());
		}
		example.setOrderByClause(" create_time desc, ord_id");
		return BeanUtil.toPagedResult(ordInfoMapper.selectByExample(example));
	}
	
	@Override
	public void saveOrdInfoImp(List<Map<String, String>> ordInfoLst, String batchId, AuthStaff authStaff,
			String mainOrdId) throws Exception {
		Date date = new Date();
		for (Map<String, String> map : ordInfoLst) {
			OrdInfoImp imp = new OrdInfoImp();
			imp.setBatchId(batchId);
			imp.setExpressNo(map.get("0"));
			imp.setRecName(map.get("1"));
			imp.setIdentityCard(map.get("2"));
			imp.setRecPhone(map.get("3"));
			imp.setRecAddr(map.get("4"));
			imp.setRecZipCode(map.get("5"));
			imp.setRecCity(map.get("6"));
			imp.setWeight(map.get("7"));
			imp.setGdsId(map.get("8"));
			imp.setNum(map.get("9"));
			imp.setCreateStaff(authStaff.getStaffCode());
			imp.setCreateTime(date);
			imp.setState("0");
			imp.setMainOrdId(mainOrdId);
			ordInfoImpMapper.insert(imp);
		}
	}
	
	@Override
	public void saveOrdInfo(String batchId, AuthStaff authStaff)
			throws Exception {
		Map<String, Map<String, List<OrdInfo>>> expressMap = new HashMap<>();
		Date date = new Date();
		OrdInfoImpExample ordInfoImpExample = new OrdInfoImpExample();
		ordInfoImpExample.createCriteria().andBatchIdEqualTo(batchId).andStateEqualTo("0");
		List<OrdInfoImp> ordImpLst = ordInfoImpMapper.selectByExample(ordInfoImpExample);
		for (OrdInfoImp imp : ordImpLst) {
			if (StringUtils.isBlank(imp.getExpressNo()) || StringUtils.isBlank(imp.getRecName())
					|| StringUtils.isBlank(imp.getIdentityCard()) || StringUtils.isBlank(imp.getRecPhone())
				 	|| StringUtils.isBlank(imp.getRecAddr()) || StringUtils.isBlank(imp.getRecZipCode())
				 	|| StringUtils.isBlank(imp.getRecCity()) || StringUtils.isBlank(imp.getWeight())
				 	|| StringUtils.isBlank(imp.getGdsId()) || StringUtils.isBlank(imp.getNum())) {
				imp.setState("2");
				imp.setErrDesc("有字段为空");
				ordInfoImpMapper.updateByPrimaryKey(imp);
				continue;
			}
			IdentityCardExample identityCardExample = new IdentityCardExample();
			identityCardExample.createCriteria().andIdentityCardEqualTo(imp.getIdentityCard());
			List<IdentityCard> identityCardLst = identityCardMapper.selectByExample(identityCardExample);
			if (CollectionUtils.isEmpty(identityCardLst)) {
				IdentityCard identityCard = new IdentityCard();
				identityCard.setBatchId(imp.getBatchId());
				identityCard.setIdentityCard(imp.getIdentityCard());
				identityCard.setName(imp.getRecName());
				identityCard.setCreateStaff(authStaff.getStaffCode());
				identityCard.setCreateTime(date);
				identityCard.setState("1");
				String code = FileUtils.getIdCard(identityCard);
				if (!"true".equals(code)) {
					imp.setState("2");
					imp.setErrDesc("身份证验证不通过");
					if ("error".equals(code)) {
						imp.setErrDesc("调用身份证验证接口报错");
					}
					ordInfoImpMapper.updateByPrimaryKey(imp);
					continue;
				}
				identityCardMapper.insert(identityCard);
			} else if (!StringUtils.equals(identityCardLst.get(0).getName(), imp.getRecName())) {
				imp.setState("2");
				imp.setErrDesc("身份证号码和人名对不上");
				ordInfoImpMapper.updateByPrimaryKey(imp);
				continue;
			}
			GdsInfoExample gdsInfoExample = new GdsInfoExample();
			gdsInfoExample.createCriteria().andGdsIdEqualTo(Long.valueOf(imp.getGdsId()))
				.andStateEqualTo("1");
			List<GdsInfo> gdsInfoLst = gdsInfoMapper.selectByExample(gdsInfoExample);
			if (CollectionUtils.isEmpty(gdsInfoLst) || gdsInfoLst.get(0) == null) {
				imp.setState("2");
				imp.setErrDesc("不存在有效商品");
				ordInfoImpMapper.updateByPrimaryKey(imp);
				continue;
			}
			GdsInfo gdsInfo = gdsInfoLst.get(0);
			int money = Integer.valueOf(imp.getNum()) * gdsInfo.getPrice();
			if (money > 2000000) {
				imp.setState("2");
				imp.setErrDesc("该用户已下单超过2万元");
				ordInfoImpMapper.updateByPrimaryKey(imp);
				continue;
			}
			OrdInfoExample ordInfoExample = new OrdInfoExample();
			ordInfoExample.createCriteria().andIdentityCardEqualTo(imp.getIdentityCard());
			List<OrdInfo> ordInfoLst = ordInfoMapper.selectByExample(ordInfoExample);
			for (OrdInfo ordInfo : ordInfoLst) {
				money += (ordInfo.getNum() * gdsInfo.getPrice());
			}
			if (money > 2000000) {
				imp.setState("2");
				imp.setErrDesc("该用户已下单超过2万元");
				ordInfoImpMapper.updateByPrimaryKey(imp);
				continue;
			}
			OrdInfo ordInfo = new OrdInfo();
			ordInfo.setImpId(imp.getId());
			ordInfo.setBatchId(batchId);
			ordInfo.setExpressNo(imp.getExpressNo());
			ordInfo.setRecName(imp.getRecName());
			ordInfo.setIdentityCard(imp.getIdentityCard());
			ordInfo.setRecPhone(imp.getRecPhone());
			ordInfo.setRecAddr(imp.getRecAddr());
			ordInfo.setRecZipCode(imp.getRecZipCode());
			ordInfo.setRecCity(imp.getRecCity());
			ordInfo.setWeight(Double.valueOf(imp.getWeight()));
			ordInfo.setGdsId(imp.getGdsId());
			ordInfo.setNum(Integer.valueOf(imp.getNum()));
			ordInfo.setCreateStaff(authStaff.getStaffCode());
			ordInfo.setCreateTime(date);
			ordInfo.setState("1");
			ordInfo.setLegalNum(gdsInfo.getLegalNum());
			ordInfo.setMeasureCode(gdsInfo.getMeasureCode());
			ordInfo.setLegalMeasureUnit(gdsInfo.getLegalMeasureUnit());
			ordInfo.setSecMeasureUnit(gdsInfo.getSecMeasureUnit());
			ordInfo.setPrice(gdsInfo.getPrice());
			ordInfo.setTotalMoney(ordInfo.getNum() * gdsInfo.getPrice());
			ordInfo.setRecordCode(gdsInfo.getRecordCode());
			ordInfo.setGdsName(gdsInfo.getGdsName());
			ordInfo.setSpec(gdsInfo.getSpec());
			ordInfo.setGdsCode(gdsInfo.getGdsCode());
			ordInfo.setMainOrdId(imp.getMainOrdId());
			Map<String, List<OrdInfo>> cardMap = expressMap.get(ordInfo.getExpressNo());
			if (cardMap == null) {
				cardMap = new HashMap<>();
				expressMap.put(ordInfo.getExpressNo(), cardMap);
			}
			List<OrdInfo> ordLst = cardMap.get(ordInfo.getIdentityCard());
			if (ordLst == null) {
				ordLst = new ArrayList<>();
				cardMap.put(ordInfo.getIdentityCard(), ordLst);
			}
			ordLst.add(ordInfo);
		}
		if (expressMap.keySet().isEmpty()) {
			return;
		}
		for (String expressNo : expressMap.keySet()) {
			Map<String, List<OrdInfo>> cardMap = expressMap.get(expressNo);
			String ordId = FileUtils.getRandomId();
			String payId = FileUtils.getRandomId();
	        Date payTime = new Date();
			for (String card : cardMap.keySet()) {
				List<OrdInfo> ordLst = cardMap.get(card);
				int custNo = 1, expressNum = 0;
				for (OrdInfo ordInfo : ordLst) {
					ordInfo.setOrdId(ordId);
					ordInfo.setPayId(payId);
					ordInfo.setPayTime(payTime);
					ordInfo.setCustNo(custNo);
					ordInfoMapper.insert(ordInfo);
					OrdInfoImp imp = new OrdInfoImp();
					imp.setId(ordInfo.getImpId());
					imp.setState("1");
					ordInfoImpMapper.updateByPrimaryKeySelective(imp);
					custNo++;
					expressNum += ordInfo.getNum();
				}
				OrdInfo ordInfo = new OrdInfo();
				ordInfo.setExpressNum(expressNum);
				OrdInfoExample example = new OrdInfoExample();
				example.createCriteria().andBatchIdEqualTo(batchId)
					.andExpressNoEqualTo(expressNo).andIdentityCardEqualTo(card);
				ordInfoMapper.updateByExampleSelective(ordInfo, example);
			}
		}
	}

	@Override
	public PagedResult<OrdInfoImp> queryOrdInfoImpByPage(OrdInfoImp imp, Integer pageNo, Integer pageSize)
			throws Exception {
		// TODO Auto-generated method stub
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 10 : pageSize;
		PageHelper.startPage(pageNo, pageSize); // startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		OrdInfoImpExample example = new OrdInfoImpExample();
		OrdInfoImpExample.Criteria criteria = example.createCriteria();		
		criteria.andBatchIdEqualTo(imp.getBatchId());
		if (StringUtils.isNotBlank(imp.getState())) {
			criteria.andStateEqualTo(imp.getState());
		}
		example.setOrderByClause(" ord_id");
		return BeanUtil.toPagedResult(ordInfoImpMapper.selectByExample(example));
	}

	@Override
	public void pay(List<String> idLst) throws Exception {
		// TODO Auto-generated method stub
        Date date = new Date();
		for (String id : idLst) {
			OrdInfo ordInfo = new OrdInfo();
			ordInfo.setId(Integer.valueOf(id));
			ordInfo.setPayTime(date);
			ordInfoMapper.updateByPrimaryKeySelective(ordInfo);
		}
	}

	@Override
	public List<OrdInfo> queryOrdInfoById(String ordId) throws Exception {
		// TODO Auto-generated method stub
		OrdInfo ordInfo = new OrdInfo();
		ordInfo.setOrdId(ordId);
		List<OrdInfo> result = ordInfoMapper.selectExportByExample(ordInfo);
		if (CollectionUtils.isEmpty(result)) {
			return Collections.emptyList();
		}
		return result;
	}
}
